﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using EOSCRM.Util ;
using EOSCRM.Domain;
using EOSCRM.Web.Common;
using EOSCRM.Dao;
using EOSCRM.Web.Shared;
using EOSCRM.Web.UserControls;


namespace EOSCRM.Web.Forms.ChucNang
{
    public partial class UngLuong : Authentication
    {
        private readonly ChamCongDao _objDao = new ChamCongDao();
        private readonly LoDao _loDao = new LoDao();
        private readonly NhanVienDao _nvDao = new NhanVienDao();
        private readonly KhuVucDao _khuVucDao = new KhuVucDao();
        private readonly CongTyDao _congtyDao = new CongTyDao();

        private UNGLUONG ItemObj
        {
            get
            {
                if (!ValidateData())
                    return null;

                var kv = new UNGLUONG
                {
                    ID=0,
                    MANV=ddlNhanVien.SelectedValue,
                    SOTIEN=ConvertUtil.ToDecimal(txtSoTien.Text.Trim()),
                    NGAYNHAP=DateTime.Now,
                    NGAYUNG=DateTime.Now,
                    LYDO=txtLyDo.Text.Trim(),
                    GHICHU=txtnotes.Text.Trim(),
                    MANVNHAP=LoginInfo.MaNV
                };
                return kv;
            }
        }

        private Mode UpdateMode
        {
            get
            {
                try
                {
                    if (Session[SessionKey.MODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.MODE]);
                        return (mode == Mode.Update.GetHashCode()) ? Mode.Update : Mode.Create;
                    }

                    return Mode.Create;
                }
                catch (Exception)
                {
                    return Mode.Create;
                }
            }
            set
            {
                Session[SessionKey.MODE] = value.GetHashCode();
            }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    ClearForm();
                    lbngayhientai.Text = DateTime.Now.ToString("dd/MM/yyyy"); 
                    LoadKhuVuc();
                    LoadLo(ddlKhuVuc.SelectedValue);
                    LoadNhanVienLo();
                    BindDataForGrid();
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
        
        private void BindDataForGrid()
        {
            var objList = _objDao.GetListUngLuong(ddlNhanVien.SelectedValue, ConvertUtil.ToDateTime(txtTuNgay.Text.Trim()), ConvertUtil.ToDateTime(txtDenNgay.Text.Trim()), ddlKhuVuc.SelectedValue, ddlLo.SelectedValue);
            gvList.DataSource = objList;
            gvList.PagerInforText = objList.Count.ToString();
            gvList.DataBind();
        }
        
        public bool ValidateData()
        {
            
            if (ddlNhanVien.SelectedValue == "%")
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Nhân viên"), ddlNhanVien.ClientID);
                return false;
            }
            try
            {
                int.Parse(txtSoTien.Text.Trim());
            }
            catch (Exception)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Lương "), txtSoTien.ClientID);
                return false;
            }

            
            return true;
        }

        private void DeleteList()
        {
            try
            {
                // Get list of ids that to be update
                var strIds = Request["listIds"];
                if ((strIds != null) && (!string.Empty.Equals(strIds)))
                {
                    //TODO: check relation before update list

                    var objs = new List<UNGLUONG>();
                    var listIds = strIds.Split(',');

                    // Kiem tra relation ship truoc khi delete
                    foreach (var ma in listIds)
                    {
                        if (_objDao.IsInUse(ma))
                        {
                            var msgIsInUse = new Message(MessageConstants.E_OBJECT_IN_USED, MessageType.Info, "chấm công với mã", ma);

                            CloseWaitingDialog();

                            ShowError(ResourceLabel.Get(msgIsInUse));
                            return;
                        }
                    }

                    //Add ma vao danh sách cần delete
                    objs.AddRange(listIds.Select(ma => _objDao.GetUngLuong(int.Parse(ma))));

                    if (objs.Count > 0)
                    {
                        var msg = _objDao.DeleteListUngLuong(objs,UserEventLog.ClientHost(),UserEventLog.ClientIP(),LoginInfo.MaNV);
                        if (msg != null)
                        {
                            CloseWaitingDialog();

                            switch (msg.MsgType)
                            {
                                case MessageType.Error:
                                    ShowError(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Info:
                                    ShowInfor(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Warning:
                                    ShowWarning(ResourceLabel.Get(msg));
                                    break;
                            }
                        }
                    }
                    else
                    {
                        CloseWaitingDialog();
                    }
                     
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        private void ClearForm()
        {
            txtSoTien.Text = "0";
            UpdateMode = Mode.Create;
            txtLyDo.Text = "";
            txtnotes.Text = "";
            LoadNhanVienLo();
        }

        private void BindKhuVuc(UNGLUONG obj)
        {
            if (obj == null)
                return;
            hdId.Value = obj.ID.ToString();
            SetControlValue(txtLyDo.ClientID, obj.LYDO);
            SetControlValue(txtnotes.ClientID, obj.GHICHU);
            SetControlValue(txtSoTien.ClientID, obj.SOTIEN.ToString());
            var manv = ddlNhanVien.Items.FindByValue(obj.MANV);
            if (manv != null)
                ddlNhanVien.SelectedIndex = ddlNhanVien.Items.IndexOf(manv);
            upnlInfor.Update();
        }
        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var makv = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "EditItem":
                        if (!string.Empty.Equals(makv))
                        {
                            var objDb = _objDao.GetUngLuong(int.Parse(makv));
                            if (objDb != null)
                            {
                                BindKhuVuc(objDb);
                                UpdateMode = Mode.Update;
                            }
                        }

                        CloseWaitingDialog();

                        break;
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            

            Message msg;

            // insert new
            if (UpdateMode == Mode.Create)
            {
                var info = ItemObj;
                if (info == null)
                {
                    CloseWaitingDialog();
                    return;
                }
                if (!HasInsertPermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }
                msg = _objDao.InsertUngLuong(info,UserEventLog.ClientHost(),UserEventLog.ClientIP(),LoginInfo.MaNV);
            }
            // update
            else
            {
                if (!HasUpdatePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }
                var ungluong = _objDao.GetUngLuong(int.Parse(hdId.Value));
                if (ungluong == null)
                {
                    ShowError("Bạn chưa chọn record để chỉnh sửa");
                    CloseWaitingDialog();
                    return;
                }
                ungluong.SOTIEN = ConvertUtil.ToDecimal(txtSoTien.Text.Trim());
                ungluong.GHICHU = txtnotes.Text.Trim();
                ungluong.LYDO = txtLyDo.Text.Trim();
                msg = _objDao.UpdateUngLuong(ungluong, UserEventLog.ClientHost(), UserEventLog.ClientIP(), LoginInfo.MaNV);
            }

            CloseWaitingDialog();

            if (msg == null) return;

            if (msg.MsgType != MessageType.Error)
            {
                ShowInfor(ResourceLabel.Get(msg));

                ClearForm();

                // Refresh grid view
                BindDataForGrid();
                
                upnlGrid.Update();
               
            }
            else
            {
                ShowError(ResourceLabel.Get(msg));
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // Authenticate
                if (!HasDeletePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                DeleteList();
                BindDataForGrid();
                upnlGrid.Update();

                CloseWaitingDialog();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseWaitingDialog();
            ClearForm();
        }
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            
            BindDataForGrid();
            CloseWaitingDialog();
        }
        private void LoadNhanVienLo()
        {
            var objList = _nvDao.GetListLo(ddlLo.SelectedValue);
            CommonFunc.BindDropDownList(ddlNhanVien, objList, "TenNV", "MaNV", true);
        }

        private void LoadKhuVuc()
        {
            var objList = _khuVucDao.GetList();
            CommonFunc.BindDropDownList(ddlKhuVuc, objList, "TenKhuVuc", "MaKhuVuc", true);
        }
        private void LoadLo(string makv)
        {
            var objList = _loDao.GetListKhuVuc(makv);
            CommonFunc.BindDropDownList(ddlLo, objList, "TenLo", "MaLo", true);
        }


        protected void ddlKhuVuc_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearForm();
            LoadLo(ddlKhuVuc.SelectedValue);
            LoadNhanVienLo();
            upnlGrid.Update();
        }

        protected void ddlLo_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearForm();
            LoadNhanVienLo();
            upnlGrid.Update();
        }

        

    }
}